const app = getApp();
const db = wx.cloud.database().collection("actor")
Page({
  data: {
    value: '',
    equipmentList: [] ,
    enable: false,
    loadingProps: {
      size: '50rpx',
    },
    isEditing: false,
    name:'',
    skill:'',
    imgUrl:'',
    location:'',
    contact:'',
    money:'',
    era:'',
    language:'',
    link:''


  },
  onLoad: function() {
    this.getEquipmentData(); // 在页面加载时调用获取设备信息的函数
  },
  
  viewDetail(e) {
    const index = e.currentTarget.dataset.index;
    console.log(index)
    const selectedItem = this.data.equipmentList[index];
    
    if (!selectedItem) {
      console.error("Selected item is undefined or null");
      return;
    }
    
    console.log(selectedItem._id)
    wx.navigateTo({
      url: '/pages/film-YY-detailed/film-YY-detailed?id=' + selectedItem._id
    });
},

  // 获取设备信息的函数
  getEquipmentData: function() {
    // 从 Cloud 数据库中获取 equipment 表中的数据
    
db.where({
  _openid: app.globalData.user_openid,
  
}).get().then(res => {
      console.log(res.data); // 确保获取到数据
  
      this.setData({
        equipmentList: res.data // 将获取的数据设置到页面的数据属性中
      });
    }).catch(err => {
      console.error(err);
    });
  },
  ready() {
    this.setData({ enable: true });
    setTimeout(() => {
      this.setData({ enable: false });
    }, 1000);
  },
  onRefresh() {
    this.setData({ enable: true });
    this.getEquipmentData();
    setTimeout(() => {
      this.setData({ enable: false });
    }, 1500); 
  }
  ,
  onScroll(e) {
    const { scrollTop } = e.detail;
    this.setData({ scrollTop });
  },
  handleDelete(e) {
    const index = e.currentTarget.dataset.index;
    const item = this.data.equipmentList[index]; 
    const id = item._id;
    
    db.doc(id).remove()
      .then(() => {
        wx.showToast({ title: '删除成功', icon: 'none' });
        this.getEquipmentData(); 
      })
      .catch(err => {
        wx.showToast({ title: '删除失败', icon: 'none' });
        console.error('Failed to delete item:', err);
      });
  },
  
  
  handleEdit(e) {
    const index = e.currentTarget.dataset.index;
    const item = this.data.equipmentList[index]; // Use equipmentList instead of imageList
    const id = item._id;
    const name = item.name; // Assuming name is the property for the actor's name
    const skill = item.skill; // Assuming skill is the property for the actor's skill
    const imgUrl = item.picture_url; // Assuming imgUrl is the property for the actor's image URL
    const location = item.location; // Assuming location is the property for the actor's location
    const contact = item.contact; // Assuming contact is the property for the actor's contact
    const money = item.money; // Assuming money is the property for the actor's salary
    const era = item.era; // Assuming era is the property for the actor's era
    const language = item.language; // Assuming language is the property for the actor's language
    const link = item.link; // Assuming link is the property for the actor's work link
    
    this.setData({
      isEditing: true,
      editId: id,
      name: name,
      skill: skill,
      imgUrl: imgUrl,
      location: location,
      contact: contact,
      money: money,
      era: era,
      language: language,
      link: link
    });
  },
  
  
  handleUpload() {
    let that = this;
    wx.chooseImage({
      success: chooseResult => {
        wx.showLoading({
          title: '上传中',
        });
        // 将图片上传至云存储空间
        wx.cloud.uploadFile({
          // 指定上传到的云路径
          cloudPath: 'groupnews/' + (new Date()).valueOf() + '.png',
          // 指定要上传的文件的小程序临时文件路径
          filePath: chooseResult.tempFilePaths[0],
          // 成功回调
          success: res => {
            console.log('上传成功', res);
            wx.hideLoading();
            wx.showToast({
              title: '上传图片成功',
            });
            if (res.fileID) {
              // 删除旧图片
              if (that.data.oldImgUrl) {
                wx.cloud.deleteFile({
                  fileList: [that.data.oldImgUrl],
                  success: deleteRes => {
                    console.log('旧图片删除成功', deleteRes);
                  },
                  fail: err => {
                    console.error('旧图片删除失败', err);
                  }
                });
              }
              that.setData({
                zhaopian: '图片如下',
                imgUrl: res.fileID
              });
            }
          },
          fail: err => {
            wx.hideLoading();
            console.error('上传失败', err);
            wx.showToast({
              title: '上传失败，请重试',
              icon: 'none'
            });
          }
        });
      },
      fail: err => {
        console.error('选择图片失败', err);
        wx.showToast({
          title: '选择图片失败，请重试',
          icon: 'none'
        });
      }
    });
  },
  

  publishRent() {
    const { editId, name, skill, imgUrl, location, contact, money, era, language, link } = this.data;
    
    // Check if required fields are filled
    if (!name || !contact ) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'error'
      });
      return;
    }
    
    // Update database
    db.doc(editId).update({
      data: {
        name: name,
        skill: skill,
        picture_url: imgUrl,
        location: location,
        contact: contact,
        money: money,
        era: era,
        language: language,
        link: link
      }
    }).then(() => {
      wx.showToast({ title: '修改成功', icon: 'none' });
      this.setData({
        isEditing: false,
        editId: null,
        name: '',
        skill: '',
        imgUrl: '',
        location: '',
        contact: '',
        money: '',
        era: '',
        language: '',
        link: ''
      });
      this.getEquipmentData(); // Refresh equipment data after edit
    }).catch(err => {
      wx.showToast({ title: '修改失败，请重试', icon: 'none' });
      console.error('修改失败:', err);
    });
  },
  
  cancelEdit() {
    this.setData({
      isEditing: false,
      editId: null,
      name: '',
      skill: '',
      imgUrl: '',
      location: '',
      contact: '',
      money: '',
      era: '',
      language: '',
      link: ''
    });
  }
   
    
});
